#!/usr/bin/python
import os
import os.path
import logging
import logging.handlers
import time
import fnmatch

_my_loggers = {}

def log(message):
    """print a message to the screen with a timestamp"""
    message = '[%s] %s' % (time.asctime(), message)
    print message

def get_logger(name='utility', type='console', level=logging.WARNING):
    '''utility function for getting the logger from the 
       python logging facility'''

    logger = None

    if name in _my_loggers.keys():
        logger = _my_loggers[name]
    else:
        console = logging.StreamHandler()
        console.setFormatter(logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s'))
        logger = logging.getLogger(name)
        logger.addHandler(console)
        logger.setLevel(level)
        _my_loggers[name] = logger

    return logger

def exec_cmd(cmd, dryrun=True, max_trial=3):
    '''make a call on system command with numbers of retry'''
    i      = 0
    rc     = 0
    output = []
    m      = None
    try_again = True
    while try_again:
        i = i + 1
        f = os.popen(cmd)
        output = f.readlines()
        rc = f.close()
        if not rc:
            try_again = False
        elif i == max_trial:
            try_again = False
        else:
            self.logger.warning("trial %d: error: %s" % (i,output))

    return (rc, map(lambda x:x.strip(),output))

def locate(pattern, root=os.curdir):
    '''Locate all files matching supplied filename pattern in and below
    supplied root directory.'''
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)